﻿using Api.Common;
using AppManager.BLL;
using AppManager.Model;
using Newtonsoft.Json.Linq;
using PushSharp.Apple;
using PushSharp.Core;
using PushSharp.Google;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web;

namespace PushTask
{
    /// <summary>
    /// pushsharp的推送
    /// </summary>
    public class Push
    {
        public static void Send()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory;
            //string certificatePath = path.Substring(0, path.TrimEnd('\\').LastIndexOf('\\')) + @"\PushManager\Certificate\";
            string certificatePath = path + @"Certificate\";
            LogHelper.WriteLongLog("path", "certfileptah:" + certificatePath);
            LogHelper.WriteLongLog("info", "开始执行");
            Stopwatch sw = new Stopwatch();
            sw.Start();
            var messageList = MessageBLL.GetSendingList();
            sw.Stop();


            if (messageList.Count() == 0)
            {
                LogHelper.WriteLongLog(LogType.info, "没有需要发送的消息list.Count==0");
                return;
            }
            else
            {
                LogHelper.WriteLongLog(LogType.info, "本次需要发送的消息list.Count=" + messageList.Count());
                LogHelper.WriteLongLog(LogType.info, "本次需要发送的消息list.Count=" + messageList.Count());
            }

            List<MessageDevice> successList = new List<MessageDevice>();
            List<MessageDevice> errorList = new List<MessageDevice>();

            //按项目分组发送
            var mg = messageList.GroupBy(s => s.Project).Select(s => new { s.Key, List = s.ToList() });
            foreach (var g in mg)
            {
                var list = g.List;

                try
                {
                    PushSharpSend.ApnsSend(certificatePath, list, successList, errorList);
                    PushSharpSend.GcmSend(list, successList, errorList);
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLongLog(LogType.error, "Push.Send发成错误：" + ex.Message);
                }
                finally
                {
                    if (successList.Count() == 0 && errorList.Count == 0)
                    {
                    }
                    else
                    {
                        MessageDeviceBLL.UpdateStatus(true, successList);
                        MessageDeviceBLL.UpdateStatus(false, errorList);
                        //LogHelper.WriteCreateNewLog(string.Format("{0} ，本次共成功发送{1}条记录,失败记录{2}", DateTime.Now, successList.Count, errorList.Count));
                    }
                }
            }

            LogHelper.WriteCreateNewLog(LogType.info, "结束执行");
        }
    }
}
